package com.mab.apipassenger.interceptor;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.msb.internalcommon.constant.TokenConstants;
import com.msb.internalcommon.dto.ResponseResult;
import com.msb.internalcommon.dto.TokenResult;
import com.msb.internalcommon.util.JwtUtils;
import com.msb.internalcommon.util.RedisPrefixUtils;
import io.netty.util.internal.StringUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Auther: jiudianliu
 * @Date: 2023/5/25 - 05 - 25 - 11:45
 * @Description: com.mab.apipassenger.intercept
 * @version: 1.0
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate ;

    //重写该接口的preHandle实现方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        boolean result = true ;
        String resultString = " " ;

        String token = request.getHeader("Authorization");
        //解析Token
        TokenResult tokenResult = JwtUtils.checkToken(token) ;
        //判断出现异常
        try {
            tokenResult = JwtUtils.parseToken(token) ;
        }catch (SignatureVerificationException e) {
            resultString = "token sign error" ;
            result = false ;
        }catch (TokenExpiredException e) {
            resultString = "token time out" ;
            result = false ;
        }catch (AlgorithmMismatchException e) {
            resultString = "token AlgorithmMismatchException" ;
            result = false ;
        }catch (Exception e) {
            resultString = "token invalid" ;
            result = false ;
        }

        if (tokenResult == null) {
            resultString = "token invalid" ;
            result = false ;
        }else{
            //拼接key
            String phone = tokenResult.getPhone();
            String identity = tokenResult.getIdentity();
            String tokenkey = RedisPrefixUtils.generatorTokenKey(phone , identity , TokenConstants.ACCESS_TOKEN_TYPE);

            //从Redis中取出Token
            String tokenRedis = stringRedisTemplate.opsForValue().get(tokenkey) ;
            //如果Redis key为空  就输出无效
            if ((StringUtils.isBlank(tokenRedis))  || (! token.trim().equals(tokenRedis.trim()))){
                resultString = "token invalid" ;
                result = false ;
            }
        }


        //比较我们传入的Token和Redis中的Token是否相等

        if (!result){
            PrintWriter out = response.getWriter() ;
            out.print(JSONObject.fromObject(ResponseResult.fail(resultString)).toString());
        }

        return result;
    }
}
